#include"UdpServer.hpp"
#include<memory>
#include<string>
#include <stdio.h>
#include<vector>
#include"Comm.hpp"
using namespace std;


void Usage(string proc)
{
    cout << "Usag : \n\t" << proc << " local_port\n" << endl;
}

vector<string> black_words = {
    "rm",
    "unlink",
    "cp",
    "mv",
    "chmod",
    "exit",
    "reboot",
    "halt",
    "shutdown",
    "kill",
    "dd",
    "vim",
    "vi",
    "nano",
    "man"

};

string OnMessageDefault(string request)
{
    return request + "[haha,got you!!]";
}

bool SafeCheck(string command)
{
    for(auto &k : black_words)
    {
        auto pos = command.find(k);
        if(pos != string::npos) return false;
    }
    return true;
}

//执行命令
//ls -a -l / rm / touch
string ExecuteCommand(string command)
{
    if(!SafeCheck(command)) return "bad man!!";
    cout << "get a message: " << command << endl;


//#include <stdio.h>
//FILE *popen(const char *command, const char *type);
//int pclose(FILE *stream);
//返回值返回到FILE中
//通过底层管道fork子进程进行命令的执行
    FILE* fp = popen(command.c_str(),"r");
    if(fp == nullptr)
    {
        return "execute error,reason is unknown";
    }

    string response;
    char buffer[1024];
    while(true)
    {
        char *s = fgets(buffer,sizeof(buffer),fp);
        if(!s) break;
        else response += buffer;
    }
    pclose(fp);
    return response.empty() ? "success" : response;
}

//./udp_sv 8888
int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    // string ip = argv[1];
    uint16_t port = stoi(argv[1]);

    unique_ptr<UdpServer> usvr = make_unique<UdpServer>(ExecuteCommand,port);
    
    usvr->Init();
    usvr->Start();

    return 0;
}
